package com.zut.chat.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zut.chat.dto.WebSocketMessage;
import com.zut.chat.entity.User;
import com.zut.chat.service.*;
import com.zut.chat.util.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * WebSocket聊天处理器
 */
@Slf4j
@Component
public class ChatWebSocketHandler extends TextWebSocketHandler {

    @Autowired
    private ChatWebSocketService chatWebSocketService;

    @Autowired(required = false)
    private RedisMessagePublisher redisMessagePublisher;

    @Autowired
    private UserService userService;

    @Autowired
    private ChatMessageService chatMessageService;

    @Autowired
    private QwenAIService qwenAIService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MessageRateLimitService messageRateLimitService;

    @Autowired
    private ChatBotAutoReplyService chatBotAutoReplyService;

    // 存储用户昵称
    private final Map<String, String> userNicknames = new ConcurrentHashMap<>();

    // 用于去重的离开消息缓存（存储 sessionId + timestamp）
    private final ConcurrentSkipListSet<String> processedLeaveMessages = new ConcurrentSkipListSet<>();

    // 定时清理过期的离开消息记录
    private final ScheduledExecutorService cleanupExecutor = Executors.newSingleThreadScheduledExecutor();

    public ChatWebSocketHandler() {
        // 每30秒清理一次过期的离开消息记录（超过1分钟的记录）
        cleanupExecutor.scheduleAtFixedRate(this::cleanupExpiredLeaveMessages, 30, 30, TimeUnit.SECONDS);
    }

    private void cleanupExpiredLeaveMessages() {
        long currentTime = System.currentTimeMillis();
        processedLeaveMessages.removeIf(key -> {
            try {
                String[] parts = key.split("_");
                if (parts.length >= 2) {
                    long timestamp = Long.parseLong(parts[parts.length - 1]);
                    return (currentTime - timestamp) > 60000; // 超过1分钟的记录删除
                }
            } catch (Exception e) {
                log.warn("清理离开消息记录时解析失败: {}", key);
            }
            return false;
        });
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String sessionId = session.getId();
        chatWebSocketService.addSession(sessionId, session);

        log.info("WebSocket连接建立: {}", sessionId);

        // 发送连接成功消息，包含真实的sessionId
        WebSocketMessage welcomeMessage = WebSocketMessage.builder()
                .type(WebSocketMessage.MessageType.SYSTEM)
                .content("连接成功！请输入您的昵称开始聊天。")
                .timestamp(LocalDateTime.now())
                .onlineCount(chatWebSocketService.getOnlineCount())
                .sessionId(sessionId)  // 添加真实的sessionId
                .build();

        chatWebSocketService.sendMessageToUser(sessionId, welcomeMessage);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String sessionId = session.getId();

        try {
            WebSocketMessage receivedMessage = objectMapper.readValue(message.getPayload(), WebSocketMessage.class);
            String content = receivedMessage.getContent();
            String senderNickname = receivedMessage.getSenderNickname();

            log.debug("收到消息 - 会话: {}, 昵称: {}, 内容: {}", sessionId, senderNickname, content);

            // 处理不同类型的消息
            switch (receivedMessage.getType()) {
                case JOIN:
                    handleUserJoin(sessionId, senderNickname);
                    break;
                case TEXT:
                    handleChatMessage(sessionId, senderNickname, content);
                    break;
                case IMAGE:
                    handleImageMessage(sessionId, senderNickname, receivedMessage.getImageUrl());
                    break;
                case GIFT:
                    handleGiftMessage(sessionId, senderNickname, receivedMessage);
                    break;
                case LEAVE:
                    handleUserLeave(sessionId, senderNickname);
                    break;
                case GET_ONLINE_USERS:
                    handleGetOnlineUsers(sessionId, senderNickname);
                    break;
                case ADMIN_KICK_USER:
                    handleAdminKickUser(sessionId, receivedMessage);
                    break;
                case ADMIN_BAN_USER:
                    handleAdminBanUser(sessionId, receivedMessage);
                    break;
                case ADMIN_UNBAN_USER:
                    handleAdminUnbanUser(sessionId, receivedMessage);
                    break;
                default:
                    log.warn("未知消息类型: {}", receivedMessage.getType());
            }
        } catch (Exception e) {
            log.error("处理WebSocket消息失败: {}", message.getPayload(), e);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("WebSocket传输错误: {}", session.getId(), exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        String sessionId = session.getId();

        log.info("WebSocket连接关闭: {}, 关闭状态: {}", sessionId, closeStatus);

        // 尝试移除用户昵称，如果返回null说明已经被处理过了
        String nickname = userNicknames.remove(sessionId);

        if (nickname != null) {
            log.info("处理异常断开连接的用户: {}, 昵称: {}", sessionId, nickname);

            // 说明用户是异常断开连接（如网络问题、浏览器崩溃等），而不是主动离开
            chatWebSocketService.removeSession(sessionId);

            // 设置用户离线状态
            userService.setUserOffline(sessionId);

            // 发布用户离开消息
            WebSocketMessage leaveMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.LEAVE)
                    .senderNickname(nickname)
                    .content(nickname + " 离开了聊天室")
                    .timestamp(LocalDateTime.now())
                    .onlineCount(chatWebSocketService.getOnlineCount())
                    .sessionId(sessionId)
                    .build();

            // 保存离开消息到数据库
            chatMessageService.saveMessage(leaveMessage);

            publishOrBroadcast(leaveMessage);
        } else {
            log.info("用户连接关闭，但已经处理过离开逻辑: {}", sessionId);

            // 确保会话被清理（防御性编程）
            chatWebSocketService.removeSession(sessionId);
            userService.setUserOffline(sessionId);
        }
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 处理用户加入
     */
        private void handleUserJoin(String sessionId, String nickname) {
        try {
            // 保存用户到数据库
            User user = userService.createOrUpdateUser(sessionId, nickname);

            userNicknames.put(sessionId, nickname);

        // 根据用户类型显示不同的加入消息
        String joinContent = nickname + " 加入了聊天室";
        if (User.UserType.ADMIN.equals(user.getUserType())) {
            joinContent = nickname + " (管理员) 加入了聊天室";
        }

        WebSocketMessage joinMessage = WebSocketMessage.builder()
                .type(WebSocketMessage.MessageType.JOIN)
                .senderNickname(nickname)
                .content(joinContent)
                .timestamp(LocalDateTime.now())
                .onlineCount(chatWebSocketService.getOnlineCount())
                .sessionId(sessionId)
                .build();

            // 保存系统消息到数据库
            chatMessageService.saveMessage(joinMessage);

            publishOrBroadcast(joinMessage);
        } catch (RuntimeException e) {
            // 昵称重复或其他错误
            WebSocketMessage errorMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.SYSTEM)
                    .content("加入失败：" + e.getMessage())
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(sessionId, errorMessage);
            log.warn("用户加入失败 - 会话: {}, 昵称: {}, 错误: {}", sessionId, nickname, e.getMessage());
        }
    }

    /**
     * 处理聊天消息
     */
    private void handleChatMessage(String sessionId, String nickname, String content) {
        if (content == null || content.trim().isEmpty()) {
            return;
        }

        // 检查用户是否被禁言
        User user = userService.findBySessionId(sessionId);
        if (user == null) {
            log.warn("找不到用户信息: {}", sessionId);
            return;
        }

        if (user.isCurrentlyBanned()) {
            // 发送禁言提示消息给用户
            String banMessage = "您已被禁言";
            if (user.getBanReason() != null) {
                banMessage += "，原因：" + user.getBanReason();
            }
            if (user.getBanExpireTime() != null) {
                banMessage += "，解禁时间：" + DateTimeUtils.formatDateTime(user.getBanExpireTime());
            } else {
                banMessage += "（永久禁言）";
            }

            WebSocketMessage warningMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.SYSTEM)
                    .content(banMessage)
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(sessionId, warningMessage);
            return;
        }

        // 检查消息发送频率限制
        if (messageRateLimitService.isRateLimited(sessionId, user.getUserType())) {
            WebSocketMessage rateLimitMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.RATE_LIMIT_WARNING)
                    .content("发送消息过于频繁，请稍后再试")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(sessionId, rateLimitMessage);
            return;
        }

        String trimmedContent = content.trim();

        WebSocketMessage textMessage = WebSocketMessage.builder()
                .type(WebSocketMessage.MessageType.TEXT)
                .senderNickname(nickname)
                .content(trimmedContent)
                .timestamp(LocalDateTime.now())
                .onlineCount(chatWebSocketService.getOnlineCount())
                .sessionId(sessionId)
                .build();

        // 记录消息发送（用于频率限制）
        messageRateLimitService.recordMessage(sessionId);

        // 保存消息到数据库
        chatMessageService.saveMessage(textMessage);

        publishOrBroadcast(textMessage);

        // 触发机器人自动回复检查
        chatBotAutoReplyService.processMessage(trimmedContent, nickname);

        // 检查是否是视频请求命令
        if (trimmedContent.contains("小视频") || trimmedContent.contains("视频") || trimmedContent.contains("片")||
            trimmedContent.contains("看视频") || trimmedContent.contains("来个视频")) {
            chatBotAutoReplyService.handleVideoRequest(nickname);
        }

        // 检查是否包含@zut机器人的消息
        if (trimmedContent.contains("@zut机器人")) {
            handleAIRobotMessage(sessionId, trimmedContent);
        }
    }

    /**
     * 处理图片消息
     */
    private void handleImageMessage(String sessionId, String nickname, String imageUrl) {
        if (imageUrl == null || imageUrl.trim().isEmpty()) {
            return;
        }

        WebSocketMessage imageMessage = WebSocketMessage.builder()
                .type(WebSocketMessage.MessageType.IMAGE)
                .senderNickname(nickname)
                .content("[图片]") // 用于数据库存储的文本描述
                .imageUrl(imageUrl.trim())
                .timestamp(LocalDateTime.now())
                .onlineCount(chatWebSocketService.getOnlineCount())
                .sessionId(sessionId)
                .build();

        // 保存消息到数据库
        chatMessageService.saveMessage(imageMessage);

        publishOrBroadcast(imageMessage);
    }

    /**
     * 处理AI机器人消息
     */
    private void handleAIRobotMessage(String sessionId, String content) {
        // 提取用户问题（去掉@zut机器人前缀）
        String userQuestion = content.replaceFirst("@[Zz]ut机器人\\s*", "").trim();
        if (userQuestion.isEmpty()) {
            userQuestion = "你好";
        }

        log.info("收到AI机器人问题 - 会话: {}, 问题: {}", sessionId, userQuestion);

        // 异步调用AI服务
        qwenAIService.getChatResponse(userQuestion)
                .subscribe(
                    aiResponse -> {
                        // AI回复成功
                        WebSocketMessage aiMessage = WebSocketMessage.builder()
                                .type(WebSocketMessage.MessageType.AI_ROBOT)
                                .senderNickname("zut机器人")
                                .content(aiResponse)
                                .timestamp(LocalDateTime.now())
                                .onlineCount(chatWebSocketService.getOnlineCount())
                                .sessionId("ai_robot")
                                .build();

                        // 保存AI消息到数据库
                        chatMessageService.saveMessage(aiMessage);

                        // 广播AI回复
                        publishOrBroadcast(aiMessage);

                        log.info("AI机器人回复成功 - 会话: {}, 回复: {}", sessionId, aiResponse);
                    },
                    error -> {
                        log.error("AI机器人回复失败 - 会话: {}", sessionId, error);

                        // 发送错误消息
                        WebSocketMessage errorMessage = WebSocketMessage.builder()
                                .type(WebSocketMessage.MessageType.AI_ROBOT)
                                .senderNickname("zut机器人")
                                .content("抱歉，我现在有点忙，请稍后再试～")
                                .timestamp(LocalDateTime.now())
                                .onlineCount(chatWebSocketService.getOnlineCount())
                                .sessionId("ai_robot")
                                .build();

                        publishOrBroadcast(errorMessage);
                    }
                );
    }



    /**
     * 处理用户离开
     */
    private void handleUserLeave(String sessionId, String nickname) {
        // 生成去重键（sessionId + 当前时间戳）
        long currentTime = System.currentTimeMillis();
        String dedupeKey = sessionId + "_" + currentTime;

        // 检查是否在短时间内已经处理过该用户的离开消息
        boolean alreadyProcessed = processedLeaveMessages.stream()
            .anyMatch(key -> key.startsWith(sessionId + "_") &&
                     (currentTime - Long.parseLong(key.split("_")[1])) < 5000); // 5秒内的重复

        if (alreadyProcessed) {
            log.info("用户 {} (session: {}) 的离开消息在5秒内已处理过，跳过重复处理", nickname, sessionId);
            return;
        }

        // 先检查用户是否已经处理过离开
        String existingNickname = userNicknames.remove(sessionId);
        if (existingNickname == null) {
            log.info("用户 {} 已经处理过离开，跳过重复处理", nickname);
            return;
        }

        // 记录已处理的离开消息
        processedLeaveMessages.add(dedupeKey);

        log.info("处理用户主动离开: {}, 昵称: {}", sessionId, nickname);

        // 设置用户离线状态
        userService.setUserOffline(sessionId);

        // 移除WebSocket会话
        chatWebSocketService.removeSession(sessionId);

        WebSocketMessage leaveMessage = WebSocketMessage.builder()
                .type(WebSocketMessage.MessageType.LEAVE)
                .senderNickname(nickname)
                .content(nickname + " 离开了聊天室")
                .timestamp(LocalDateTime.now())
                .onlineCount(chatWebSocketService.getOnlineCount())
                .sessionId(sessionId)
                .build();

        // 保存离开消息到数据库
        chatMessageService.saveMessage(leaveMessage);

        publishOrBroadcast(leaveMessage);
    }

    /**
     * 处理礼物消息
     */
    private void handleGiftMessage(String sessionId, String senderNickname, WebSocketMessage receivedMessage) {
        if (receivedMessage.getGiftName() == null || receivedMessage.getGiftName().trim().isEmpty()) {
            log.warn("收到无效的礼物消息 - 会话: {}, 发送者: {}, 礼物名称: {}", sessionId, senderNickname, receivedMessage.getGiftName());
            return;
        }

        String giftName = receivedMessage.getGiftName().trim();

        WebSocketMessage giftMessage = WebSocketMessage.builder()
                .type(WebSocketMessage.MessageType.GIFT)
                .senderNickname(senderNickname)
                .content(senderNickname + " 送出了 " + giftName)
                .giftName(giftName)
                .giftIcon(receivedMessage.getGiftIcon())
                .giftAnimation(receivedMessage.getGiftAnimation())
                .giftValue(receivedMessage.getGiftValue())
                .timestamp(LocalDateTime.now())
                .onlineCount(chatWebSocketService.getOnlineCount())
                .sessionId(sessionId)
                .build();

        // 保存礼物消息到数据库
        chatMessageService.saveMessage(giftMessage);

        // 广播礼物消息
        publishOrBroadcast(giftMessage);

        log.info("处理礼物消息 - 会话: {}, 发送者: {}, 礼物: {}", sessionId, senderNickname, giftName);
    }

    /**
     * 处理获取在线用户列表请求
     */
    private void handleGetOnlineUsers(String sessionId, String senderNickname) {
        try {
            List<User> onlineUsers = userService.searchOnlineUsers(null);

            List<WebSocketMessage.OnlineUserInfo> userInfoList = onlineUsers.stream()
                    .map(user -> WebSocketMessage.OnlineUserInfo.builder()
                            .sessionId(user.getSessionId())
                            .nickname(user.getNickname())
                            .userType(user.getUserType().name())
                            .lastActiveTime(user.getLastActiveTime())
                            .build())
                    .collect(java.util.stream.Collectors.toList());

            WebSocketMessage onlineUsersMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ONLINE_USERS)
                    .content("在线用户列表")
                    .timestamp(LocalDateTime.now())
                    .onlineUsers(userInfoList)
                    .onlineCount(userInfoList.size())
                    .build();

            chatWebSocketService.sendMessageToUser(sessionId, onlineUsersMessage);
        } catch (Exception e) {
            log.error("获取在线用户列表失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 处理管理员踢出用户请求
     */
    private void handleAdminKickUser(String adminSessionId, WebSocketMessage message) {
        try {
            // 验证管理员权限
            if (!userService.isAdmin(adminSessionId)) {
                WebSocketMessage errorMessage = WebSocketMessage.builder()
                        .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                        .content("权限不足，仅管理员可以执行此操作")
                        .timestamp(LocalDateTime.now())
                        .operationResult(false)
                        .operationMessage("权限不足")
                        .build();

                chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
                return;
            }

            String targetSessionId = message.getTargetSessionId();
            if (targetSessionId == null || targetSessionId.trim().isEmpty()) {
                WebSocketMessage errorMessage = WebSocketMessage.builder()
                        .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                        .content("目标用户会话ID不能为空")
                        .timestamp(LocalDateTime.now())
                        .operationResult(false)
                        .operationMessage("参数错误")
                        .build();

                chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
                return;
            }

            // 获取目标用户信息
            User targetUser = userService.findBySessionId(targetSessionId);
            if (targetUser == null) {
                WebSocketMessage errorMessage = WebSocketMessage.builder()
                        .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                        .content("目标用户不存在")
                        .timestamp(LocalDateTime.now())
                        .operationResult(false)
                        .operationMessage("用户不存在")
                        .build();

                chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
                return;
            }

            // 不能踢出管理员
            if (User.UserType.ADMIN.equals(targetUser.getUserType())) {
                WebSocketMessage errorMessage = WebSocketMessage.builder()
                        .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                        .content("不能踢出管理员用户")
                        .timestamp(LocalDateTime.now())
                        .operationResult(false)
                        .operationMessage("权限限制")
                        .build();

                chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
                return;
            }

            // 强制用户下线
            boolean success = userService.forceUserOffline(targetSessionId);

            if (success) {
                // 向目标用户发送踢出消息
                WebSocketMessage kickMessage = WebSocketMessage.builder()
                        .type(WebSocketMessage.MessageType.ADMIN_KICK_USER)
                        .content("您已被管理员踢出聊天室" + (message.getContent() != null && !message.getContent().trim().isEmpty() ? "，原因：" + message.getContent() : ""))
                        .timestamp(LocalDateTime.now())
                        .build();

                chatWebSocketService.sendMessageToUser(targetSessionId, kickMessage);

                // 广播用户被踢出的系统消息
                WebSocketMessage systemMessage = WebSocketMessage.builder()
                        .type(WebSocketMessage.MessageType.SYSTEM)
                        .content(targetUser.getNickname() + " 被管理员踢出了聊天室")
                        .timestamp(LocalDateTime.now())
                        .onlineCount(chatWebSocketService.getOnlineCount())
                        .build();

                publishOrBroadcast(systemMessage);

                // 移除WebSocket会话
                chatWebSocketService.removeSession(targetSessionId);

                // 向管理员发送操作成功消息
                WebSocketMessage successMessage = WebSocketMessage.builder()
                        .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                        .content("用户 " + targetUser.getNickname() + " 已被踢出")
                        .timestamp(LocalDateTime.now())
                        .operationResult(true)
                        .operationMessage("操作成功")
                        .build();

                chatWebSocketService.sendMessageToUser(adminSessionId, successMessage);
            } else {
                WebSocketMessage errorMessage = WebSocketMessage.builder()
                        .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                        .content("踢出用户失败")
                        .timestamp(LocalDateTime.now())
                        .operationResult(false)
                        .operationMessage("操作失败")
                        .build();

                chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
            }
        } catch (Exception e) {
            log.error("处理管理员踢出用户请求失败: {}", e.getMessage(), e);

            WebSocketMessage errorMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                    .content("踢出用户失败：" + e.getMessage())
                    .timestamp(LocalDateTime.now())
                    .operationResult(false)
                    .operationMessage("系统错误")
                    .build();

            chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
        }
    }

    /**
     * 处理管理员禁言用户
     */
    private void handleAdminBanUser(String adminSessionId, WebSocketMessage message) {
        // 验证管理员权限
        if (!userService.isAdmin(adminSessionId)) {
            WebSocketMessage errorMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                    .operationResult(false)
                    .operationMessage("权限不足，只有管理员才能禁言用户")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
            return;
        }

        String targetSessionId = message.getTargetSessionId();
        if (targetSessionId == null || targetSessionId.trim().isEmpty()) {
            WebSocketMessage errorMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                    .operationResult(false)
                    .operationMessage("目标用户会话ID不能为空")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
            return;
        }

        User targetUser = userService.findBySessionId(targetSessionId);
        if (targetUser == null) {
            WebSocketMessage errorMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                    .operationResult(false)
                    .operationMessage("目标用户不存在")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
            return;
        }

        // 不能禁言管理员
        if (User.UserType.ADMIN.equals(targetUser.getUserType())) {
            WebSocketMessage errorMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                    .operationResult(false)
                    .operationMessage("不能禁言管理员用户")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
            return;
        }

        String banReason = message.getContent() != null ? message.getContent().trim() : "违规行为";
        // 默认禁言24小时，可以根据需要调整
        LocalDateTime banExpireTime = LocalDateTime.now().plusHours(24);

        boolean success = userService.banUser(targetSessionId, banReason, banExpireTime);

        if (success) {
            // 向目标用户发送禁言通知
            WebSocketMessage banNotification = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.SYSTEM)
                    .content("您已被管理员禁言，原因：" + banReason + "，解禁时间：" + DateTimeUtils.formatDateTime(banExpireTime))
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(targetSessionId, banNotification);

            // 向管理员发送操作结果
            WebSocketMessage resultMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                    .operationResult(true)
                    .operationMessage("用户 " + targetUser.getNickname() + " 已被禁言")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(adminSessionId, resultMessage);

            log.info("管理员 {} 禁言了用户 {}, 原因: {}", adminSessionId, targetUser.getNickname(), banReason);
        } else {
            WebSocketMessage errorMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                    .operationResult(false)
                    .operationMessage("禁言操作失败")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
        }
    }

    /**
     * 处理管理员解除禁言
     */
    private void handleAdminUnbanUser(String adminSessionId, WebSocketMessage message) {
        // 验证管理员权限
        if (!userService.isAdmin(adminSessionId)) {
            WebSocketMessage errorMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                    .operationResult(false)
                    .operationMessage("权限不足，只有管理员才能解除禁言")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
            return;
        }

        String targetSessionId = message.getTargetSessionId();
        if (targetSessionId == null || targetSessionId.trim().isEmpty()) {
            WebSocketMessage errorMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                    .operationResult(false)
                    .operationMessage("目标用户会话ID不能为空")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
            return;
        }

        User targetUser = userService.findBySessionId(targetSessionId);
        if (targetUser == null) {
            WebSocketMessage errorMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                    .operationResult(false)
                    .operationMessage("目标用户不存在")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
            return;
        }

        boolean success = userService.unbanUser(targetSessionId);

        if (success) {
            // 向目标用户发送解禁通知
            WebSocketMessage unbanNotification = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.SYSTEM)
                    .content("您的禁言已被管理员解除，可以正常聊天了")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(targetSessionId, unbanNotification);

            // 向管理员发送操作结果
            WebSocketMessage resultMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                    .operationResult(true)
                    .operationMessage("用户 " + targetUser.getNickname() + " 的禁言已解除")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(adminSessionId, resultMessage);

            log.info("管理员 {} 解除了用户 {} 的禁言", adminSessionId, targetUser.getNickname());
        } else {
            WebSocketMessage errorMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.ADMIN_OPERATION_RESULT)
                    .operationResult(false)
                    .operationMessage("解除禁言操作失败")
                    .timestamp(LocalDateTime.now())
                    .build();

            chatWebSocketService.sendMessageToUser(adminSessionId, errorMessage);
        }
    }

    /**
     * 发布消息到Redis或直接本地广播
     */
    private void publishOrBroadcast(WebSocketMessage message) {
        if (redisMessagePublisher != null) {
            // 使用Redis发布订阅模式
            redisMessagePublisher.publishMessage(message);
        } else {
            // 直接本地广播
            chatWebSocketService.broadcastMessage(message);
        }
    }
}
